<!DOCTYPE html>
<html>

<head>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>H+ 后台主题UI框架 - 文件管理器</title>
    <meta name="keywords" content="H+后台主题,后台bootstrap框架,会员中心主题,后台HTML,响应式后台">
    <meta name="description" content="H+是一个完全响应式，基于Bootstrap3最新版本开发的扁平化主题，她采用了主流的左右两栏式布局，使用了Html5+CSS3等现代技术">

    <link rel="shortcut icon" href="favicon.ico">
    <link href="css/bootstrap.min.css?v=3.3.6" rel="stylesheet">
    <link href="css/font-awesome.css?v=4.4.0" rel="stylesheet">

    <link href="css/animate.css" rel="stylesheet">
    <link href="css/style.css?v=4.1.0" rel="stylesheet">
    
    <link href="clipboard/tether/css/tether.min.css" rel="stylesheet">
    <link href="clipboard/context-menu.css" rel="stylesheet">
    
    <link href="css/plugins/jsTree/style.min.css" rel="stylesheet">
    
    <link href="plugins/bootstrap-switch/css/bootstrap-switch.min.css" rel="stylesheet">
    
    <link href="bootstrap-pagination-0.6.2/bootstrap-pagination.css" rel="stylesheet">

	<link rel="stylesheet" href="js/jqcloud/jqcloud.min.css">

	<link rel="stylesheet" href="bootoast/bootoast.css" type="text/css">
    
    <!--<link href="/picimage/style.css" type="text/css" rel="stylesheet">-->
    <!--<link href="/picimage/swiper.min.css" type="text/css" rel="stylesheet">-->
    
	<style>
        .jstree-open > .jstree-anchor > .fa-folder:before {
            content: "\f07c";
        }
        .jstree-default .jstree-icon .none {
            width: 0;
        }
    </style>
</head>

<body class="gray-bg">
    <div class="wrapper wrapper-content animated fadeInUp">
        <div class="row">
        	<div class="col-sm-12">
        	<div class="ibox">
                <div class="ibox-title">
                    <h5>图片管理</h5>
                </div>
                <div class="ibox-content">
                    
                    <div class="row m-b-sm m-t-sm">
			            <div class="col-sm-3">
			                <div class="ibox float-e-margins">
			                    <div class="ibox-content" style="border-top-width: 0;">
			                        <div class="file-manager">
			                            <!--<h5>显示</h5>-->
			                            <div>
				                            <div style="width: 50%; float: left;">
												<font style="font-weight: 600; font-size: 12px;">递归&nbsp;:</font>
										 		<input id="recursive_switch" type="checkbox"/>
											</div>
											<div style="width: 50%; float: left;">
												<font style="font-weight: 600; font-size: 12px;">预览&nbsp;:</font>
										 		<input id="loading_switch" type="checkbox"/>
											</div>
										</div>
										<div class="clearfix" style="padding-bottom: 15px;"></div>
										
                                        <h5>目录树&nbsp;<a id="refresh_id"><i class="fa fa-spinner"></i></a></h5>
			                            <div id="jstree">
				                            <ul>
				                                <li class="jstree-open">image
				                                    <ul>
				                                        <li class="jstree-open">工作
				                                            <ul>
				                                                <li>public</li>
				                                                <li>private</li>
				                                            </ul>
				                                        </li>
				                                        <li class="jstree-open">旅游
				                                            <ul>
				                                                <li>public</li>
				                                                <li>private</li>
				                                            </ul>
				                                        </li>
				                                        <li class="jstree-open">生活
				                                            <ul>
				                                                <li>public</li>
				                                                <li>private</li>
				                                            </ul>
				                                        </li>
				                                        <li class="jstree-open">随拍
				                                            <ul>
				                                                <li>public</li>
				                                                <li>private</li>
				                                            </ul>
				                                        </li>
				                                        <li class="jstree-open">未分类
				                                            <ul>
				                                                <li>public</li>
				                                                <li>private</li>
				                                            </ul>
				                                        </li>
				                                    </ul>
				                                </li>
				                            </ul>
				                        </div>
			                            <div class="clearfix"></div>
			                            
			                            <div class="hr-line-dashed"></div>
			                            <h5>标签</h5>
										<div id="tag_cloud">
											<ul id="tag_list" class="tag-list" style="padding: 0">
												<!--<li><a href="file_manager.html">鼠标</a>
												</li>
												<li><a href="file_manager.html">g502</a>
												</li>
												<li><a href="file_manager.html">家庭</a>
												</li>
												<li><a href="file_manager.html">孩子</a>
												</li>
												<li><a href="file_manager.html">假期</a>
												</li>
												<li><a href="file_manager.html">音乐</a>
												</li>
												<li><a href="file_manager.html">照片</a>
												</li>
												<li><a href="file_manager.html">电影</a>
												</li>-->
											</ul>
										</div>
			                            <div class="clearfix"></div>
			                            
			                            <div class="hr-line-dashed"></div>
			                            <button type="button" class="btn btn-primary btn-block" onclick="webUploader();" >上传文件</button>
			                        </div>
			                    </div>
			                </div>
			            </div>
			            <div class="col-sm-9 animated fadeInRight">
					        <div class="row m-b-sm m-t-sm">
		                        <div id="botton_group_id" class="col-md-7" style="padding-left: 0;">
		                            <button type="button" id="all_none_select_id" class="btn btn-white btn-sm" onclick="selectAll();"><i class="fa fa-signing"></i>&nbsp;全选/全不选</button>
		                            <button type="button" id="batch_pass_id" class="btn btn-white btn-sm" onclick="batchDownload();"><i class="fa fa-cloud-download"></i>&nbsp;批量下载</button>
		                            <button type="button" id="batch_trash_id" class="btn btn-white btn-sm" onclick="batch_delete();"><i class="fa fa-trash"></i>&nbsp;批量删除</button>
									<div class="btn-group">
										<button type="button" class="btn btn-white btn-sm dropdown-toggle" data-toggle="dropdown"><i class="fa fa-institution "></i>&nbsp;设置为
											<span class="caret"></span>
										</button>
										<ul class="dropdown-menu" role="menu">
											<li><a href="javascript:;" onclick="_batchSetObjectAcl(2);">共有读</a></li>
											<li><a href="javascript:;" onclick="_batchSetObjectAcl(1);">私有读</a></li>
										</ul>
									</div>
									<div class="btn-group">
										<button type="button" class="btn btn-white btn-sm dropdown-toggle" data-toggle="dropdown"><i class="fa fa-random"></i>&nbsp;移动到
											<span class="caret"></span>
										</button>
										<ul class="dropdown-menu" role="menu">
<!--											<li><a href="#">功能1</a></li>-->
											<li><div id="menu_tree_id"></div></li>
										</ul>
									</div>
									<button type="button" id="batch_recycle_id" class="btn btn-white btn-sm" onclick="batch_recycle();"><i class="fa fa-truck"></i>&nbsp;移到回收站</button>
								</div>
		                        <div class="col-md-5">
									<div class="input-group pull-right">
		                                <input id="search_input_id" type="text" placeholder="请输入搜索内容..." class="input-sm form-control">
		                                <span class="input-group-btn">
		                                    <button id="search_button_id" class="btn btn-sm btn-primary">&nbsp;搜索</button>
		                                </span>
		                            </div>
		                        </div>
		                    </div>
			                <div class="row gray-bg">
			                    <div class="col-sm-12" id="file_container_id" style="padding-top: 10px;">
			                        <div class="file-box leftClick rightClick" style="position: relative;" onmousedown="setGlobalObject(this)" url="https://xxx/1.jpg">
			                            <div class="file">
			                                <div class="icon" align="center">
			                                    <i class="fa fa-image"></i>
			                                </div>
			                                <div class="file-name" align="center">
			                                    <!--Document_2014.doc
			                                    <br/>-->
			                                    <small style="align-content: center;">时间：2014-10-13</small>
			                                </div>
			                            </div>
			                            <span style="position:absolute; right:0; top:1%; margin-right: 20px;">
									  		<img style="position: relative; top: 0; right: 0; border: 0;" src="img/ribbon_public.png">
									  	</span>
									  	<span class="select" style="position:absolute; right:0; top:1%; margin-right: 20px; display: none;" url="https://xxx/1.jpg">
									  		<img style="position: relative; bottom: 10px; right: 0; border: 0;" src="img/select.png">
									  	</span>
			                        </div>
			                        
			                        <div class="file-box leftClick rightClick" style="position: relative;" onmousedown="setGlobalObject(this)" url="https://xxx/1.jpg">
			                            <div class="file">
			                                <div class="image" align="center" style="display:flex;justify-content:center;align-items:center;">
												<img alt="image" class="img-responsive" src="img/50.png">
			                                </div>
			                                <div class="file-name" align="center">
			                                    <!--Italy street.jpg
			                                    <br/>-->
			                                    <small style="align-content: center;">时间：2014-10-13</small>
			                                </div>
			                            </div>
			                            
			                            <span style="position:absolute; right:0; top:1%; margin-right: 20px;">
									  		<img style="position: relative; top: 0; right: 0; border: 0;" src="img/ribbon_private.png">
									  	</span>
									  	<span class="select" style="position:absolute; right:0; top:1%; margin-right: 20px; display: none;" url="https://xxx/1.jpg">
									  		<img style="position: relative; bottom: 10px; right: 0; border: 0;" src="img/select.png">
									  	</span>
			                        </div>
			                        
			                        
			                    </div>
			                    <!--分页-->
								<div class="text-center">
									<!-- 下面是控制分页控件，必须要是ul元素才行 -->
									<ul id='page_element_id1' class="pagination pagination-lg" style="margin: 0 0;"></ul>
									<ul id='page_element_id2' class="pagination pagination-lg" style="margin: 0 0;"></ul>
								</div>
			                </div>
			            </div>
            		</div>
            		
            	</div>
            </div>
        </div>
        </div>
    </div>

<!-- 全局js -->
<script src="js/jquery.min.js?v=2.1.4"></script>
<script src="js/bootstrap.min.js?v=3.3.6"></script>
<script src="js/content.js?v=1.0.0"></script>
<script src="js/layer/layer.js"></script>

<script src="clipboard/tether/js/tether.min.js"></script>
<script src="clipboard/jquery.context-menu.min.js"></script>

<script src="bootstrap-pagination-0.6.2/bootstrap-pagination.js"></script>

<!-- jsTree plugin javascript -->
<script src="js/plugins/jsTree/jstree.min.js"></script>

<script src="plugins/bootstrap-switch/js/bootstrap-switch.min.js"></script>

<script src="js/common.js"></script>

<script src="js/jqcloud/jqcloud.js"></script>

<script src="bootoast/bootoast.js" type="text/javascript"></script>

<script src="js/common.js" type="text/javascript"></script>
<script src="websocket/sockjs.min.js" type="text/javascript"></script>
<script src="websocket/stomp.min.js" type="text/javascript"></script>

<script type="text/javascript">

var global_currentPage = 1;
var global_pageSize = 15;

var global_object = null;

var global_path = "image/";
var global_cos_type = 0;
var global_root_path= "image/";
var is_upload_success = false;

var select_all_flag = 'all';

var global_is_search = false;

$(function() {

	//0、左侧栏开关按钮
	// 注意：初始化就用链式配置，且state属性的设置一定放在最后，不知道为什么，哈哈
	$('#recursive_switch').bootstrapSwitch('onText','ON').bootstrapSwitch('offText','OFF').bootstrapSwitch('size','mini').bootstrapSwitch('state',false);
	// 添加按钮切换事件
	$('#recursive_switch').bootstrapSwitch('onSwitchChange', function(event, state) {
    	if(state == true) {
    		console.log('on');
    	} else {
    		console.log('off');
    	}
    });
    
    // 注意：初始化就用链式配置，且state属性的设置一定放在最后，不知道为什么，哈哈
	$('#loading_switch').bootstrapSwitch('onText','ON').bootstrapSwitch('offText','OFF').bootstrapSwitch('size','mini').bootstrapSwitch('state',false);
	// 添加按钮切换事件
	$('#loading_switch').bootstrapSwitch('onSwitchChange', function(event, state) {
    	if(state == true) {
    		console.log('on');
    	} else {
    		console.log('off');
    	}
    });

	//单击搜索按钮
	$('#search_button_id').click(function () {
		submitSearch(global_cos_type, global_root_path, 1, 15);
	});

})

function selectAll() {
	// 获取所有的复选框
	var selElements=document.getElementsByClassName('select');
	if(select_all_flag == 'all') {
		for(var i=0;i<selElements.length;i++) {
			var sel=selElements[i];
			$(sel).css('display','block');
		}
		select_all_flag = 'none';
	} else if(select_all_flag == 'none') {
		for(var i=0;i<selElements.length;i++) {
			var sel=selElements[i];
			$(sel).css('display','none');
		}
		select_all_flag = 'all';
	}
}

// 右键图片显示菜单
function setGlobalObject(obj) {
	global_object = obj;
}

/**
 * 复制外链
 */
function copyOuterLink() {
	var input = document.createElement('input');
	document.body.appendChild(input);
 	input.setAttribute('value', $(global_object).attr('url'));
	input.select();
	if (document.execCommand('copy')) {
		parent.layer.msg('复制成功！', {
			icon: 1,
			time: 1000
		});
	} else {
		parent.layer.msg('复制失败！', {
			icon: 2,
			time: 1000
		});
	}
    document.body.removeChild(input);
}

function myBrowser() {
	var userAgent = navigator.userAgent; //取得浏览器的userAgent字符串
	if (userAgent.indexOf("OPR") > -1) {
		return "Opera";
	} //判断是否Opera浏览器 OPR/43.0.2442.991
	if (userAgent.indexOf("Firefox") > -1) {
		return "FF";
	} //判断是否Firefox浏览器  Firefox/51.0
	if (userAgent.indexOf("Trident") > -1) {
		return "IE";
	} //判断是否IE浏览器  Trident/7.0; rv:11.0
	if (userAgent.indexOf("Edge") > -1) {
		return "Edge";
	} //判断是否Edge浏览器  Edge/14.14393
	if (userAgent.indexOf("Chrome") > -1) {
		return "Chrome";
	} // Chrome/56.0.2924.87
	if (userAgent.indexOf("Safari") > -1) {
		return "Safari";
	} //判断是否Safari浏览器 AppleWebKit/534.57.2 Version/5.1.7 Safari/534.57.2
}

function convertBase64ToBlob(base64, contentType) {
	var bytes = window.atob(base64);
	var	n = bytes.length;
	var uint8Array = new Uint8Array(n);
	while(n--){
		uint8Array[n] = bytes.charCodeAt(n);
	}
	return new Blob([uint8Array], { type: contentType });
}

/**
 * 单文件下载
 */
function download() {
	//图片格式和PDF
	var key = $(global_object).attr('key');
	$.ajax({
		type: "POST",
		url: "/cos/download",
		dataType: "json",
		async: true,
		data: {
			"key": key
		},
		success: function (res) {
			if (res.code == 0) {
				var base64 = res.data.base64;
				var contentType = res.data.contentType;
				var blob = convertBase64ToBlob(base64, contentType); // 转为blob对象
				var fileName = res.data.fileName;
				if (myBrowser() == "IE") {
					window.navigator.msSaveBlob(blob, fileName);
				} else if (myBrowser() == "FF") {
					window.location.href = url;
				} else {
					var a = document.createElement("a");
					a.download = fileName;
					a.href = window.URL.createObjectURL(blob);
					a.click();
				}

			} else {
				parent.layer.msg('下载文件失败！', {
					icon: 2,
					time: 1000
				});
			}
		}
	});
}

function batchDownload() {
	var keysStr = "";

	// 获取所有已选中
	var selElements=document.getElementsByClassName('select');
	$(selElements).each(function () {
		if($(this).css("display")=="block"){
			keysStr = keysStr + "," + $(this).attr("key");
		}
	});

	if(keysStr == null || keysStr == "") {
		parent.layer.msg('请先选择要下载的文件！', {
			icon: 2,
			time: 1000
		});
		return;
	}

	keysStr = keysStr.substring(1);
	$.ajax({
		type: "POST",
		url: "/cos/batchDownload",
		dataType: "json",
		async: true,
		data: {
			"keysStr": keysStr
		},
		success: function (res) {
			if (res.code == 0) {
				var base64 = res.data.base64;
				var contentType = res.data.contentType;
				var blob = convertBase64ToBlob(base64, contentType); // 转为blob对象
				var fileName = res.data.fileName;
				if (myBrowser() == "IE") {
					window.navigator.msSaveBlob(blob, fileName);
				} else if (myBrowser() == "FF") {
					window.location.href = url;
				} else {
					var a = document.createElement("a");
					a.download = fileName;
					a.href = window.URL.createObjectURL(blob);
					a.click();
				}

			} else {
				parent.layer.msg('批量下载文件失败！', {
					icon: 2,
					time: 1000
				});
			}
		}
	});
}

/**
 * 图片预览
 */
function preview() {
	var key = $(global_object).attr('key');
	var url = $(global_object).attr('url');
	var fileName = $(global_object).attr('fileName');

	var config = {title: fileName, src: url};
	var img = new Image();
	img.onload = function() {//避免图片还未加载完成无法获取到图片的大小
		//避免图片太大，导致弹出展示超出了网页显示访问，所以图片大于浏览器时下窗口可视区域时，进行等比例缩小。
		var max_height = $(window).height() - 100;
		var max_width = $(window).width();
		//rate1，rate2，rate3 三个比例中取最小的。
		var rate1 = max_height/img.height;
		var rate2 = max_width/img.width;
		var rate3 = 1;
		var rate = Math.min(rate1,rate2,rate3);
		//等比例缩放
		config.height = img.height * rate; //获取图片高度
		config.width = img.width  * rate; //获取图片宽度

		var imgHtml = "<img id='preview_id' src='" + img.src + "' width='"+config.width+"px' height='"+config.height+"px'/>";
		layer.open({
			type: 1,
			shade: 0.4,
			offset: 'auto',
			area: [config.width + 'px',config.height + 42 +'px'], ////宽，高
			shadeClose:true,
			scrollbar: false,
			title: config.title, //不显示标题
			content: imgHtml, //捕获的元素，注意：最好该指定的元素要存放在body最外层，否则可能被其它的相对元素所影响
			cancel: function () {
				//layer.msg('捕获就是从页面已经存在的元素上，包裹layer的结构', { time: 5000, icon: 6 });
			}
		});
	}
	img.onerror = function () {
		$.ajax({
			type: "POST",
			url: "/cos/download",
			dataType: "json",
			async: true,
			data: {
				"key": key
			},
			success: function (res) {
				if (res.code == 0) {
					var base64 = res.data.base64;
					var contentType = res.data.contentType;
					img.src = "data:"+contentType+";base64," + base64;
				} else {
					parent.layer.msg('预览图片失败！', {
						icon: 2,
						time: 1000
					});
				}
			}
		});
	}
	img.src = config.src;
}

/**
 * 重命名
 */
function rename() {
	var key = $(global_object).attr('key');
	var origin_name = $(global_object).attr('fileName');
	origin_name = origin_name.substring(0, origin_name.lastIndexOf('.'));
	var file_extension = key.substring(key.lastIndexOf('.'));
	layer.prompt({
		value: origin_name,
		title: '重命名'}, function(val, index){
		$.ajax({
			type: "POST",
			url: "/cos/rename",
			dataType: "json",
			async: true,
			data: {
				"key": key,
				"newFileName": val + file_extension
			},
			success: function (res) {
				if (res.code == 0) {
					parent.layer.msg('重命名成功！', {
						icon: 1,
						time: 1000
					});
					getPage(global_path, global_currentPage, global_pageSize, null);

				} else if(res.code == 2) {
					parent.layer.msg('重命名成功！请手动修改mysql和es中该文件的名称！', {
						icon: 2,
						time: 1000
					});
				} else if(res.code == 3) {
					parent.layer.msg('重命名成功！请手动修改es中该文件的名称！', {
						icon: 2,
						time: 1000
					});
				} else {
					parent.layer.msg('重命名成功！', {
						icon: 2,
						time: 1000
					});
				}
			}
		});

		layer.close(index);
	});
}

/**
 * 单文件删除
 */
function _delete() {
	parent.layer.confirm('确定删除吗？', {
		btn: ['确定','取消'] //按钮
	}, function() {
		var key = $(global_object).attr('key');
		$.ajax({
			type: "POST",
			url: "/cos/batchDelete",
			dataType: "json",
			async: true,
			data: {
				"keysStr": key
			},
			success: function (res) {
				if (res.code == 0) {
					parent.layer.msg('删除成功！', {
						icon: 1,
						time: 1000
					});
					getPage(global_path, global_currentPage, global_pageSize, null);

				} else if(res.code == 2) {
					parent.layer.msg('删除失败！请确认mysql和es中是否已删除该文件！', {
						icon: 2,
						time: 1000
					});
				} else if(res.code == 3) {
					parent.layer.msg('删除失败！请确认es中是否已删除该文件！', {
						icon: 2,
						time: 1000
					});
				} else {
					parent.layer.msg('删除失败！', {
						icon: 2,
						time: 1000
					});
				}
			}
		});
	});
}

/**
 * 批量删除
 */
function batch_delete() {
	var keysStr = "";

	// 获取所有已选中
	var selElements = document.getElementsByClassName('select');
	$(selElements).each(function () {
		if ($(this).css("display") == "block") {
			keysStr = keysStr + "," + $(this).attr("key");
		}
	});

	if (keysStr == null || keysStr == "") {
		parent.layer.msg('请先选择要删除的文件！', {
			icon: 2,
			time: 1000
		});
		return;
	}

	keysStr = keysStr.substring(1);
	parent.layer.confirm('确定删除吗？', {
		btn: ['确定','取消'] //按钮
	}, function() {
		$.ajax({
			type: "POST",
			url: "/cos/batchDelete",
			dataType: "json",
			async: true,
			data: {
				"keysStr": keysStr
			},
			success: function (res) {
				if (res.code == 0) {
					parent.layer.msg('删除成功！', {
						icon: 1,
						time: 1000
					});
					getPage(global_path, global_currentPage, global_pageSize, null);

				} else if (res.code == 2) {
					parent.layer.msg('删除失败！请确认mysql和es中是否已删除该文件！', {
						icon: 2,
						time: 1000
					});
				} else if (res.code == 3) {
					parent.layer.msg('删除失败！请确认es中是否已删除该文件！', {
						icon: 2,
						time: 1000
					});
				} else {
					parent.layer.msg('删除失败！', {
						icon: 2,
						time: 1000
					});
				}
			}
		});
	});
}

/**
 * 移动到回收站
 */
function recycle() {
	var key = $(global_object).attr('key');
	batch_move(key, 'recycle/');
}

/**
 * 批量移动到回收站
 */
function batch_recycle() {
	var keysStr = "";

	// 获取所有已选中
	var selElements = document.getElementsByClassName('select');
	$(selElements).each(function () {
		if ($(this).css("display") == "block") {
			keysStr = keysStr + "," + $(this).attr("key");
		}
	});

	if (keysStr == null || keysStr == "") {
		parent.layer.msg('请先选择要移动的文件！', {
			icon: 2,
			time: 1000
		});
		return;
	}
	keysStr = keysStr.substring(1);
	batch_move(keysStr, 'recycle/');
}

/**
 *  批量移动
 */
function batch_move(keysStr, destDirPath) {
	$.ajax({
		type: "POST",
		url: "/cos/batchMove",
		dataType: "json",
		async: true,
		data: {
			"keysStr": keysStr,
			"destDirPath": destDirPath
		},
		success: function (res) {
			if (res.code == 0) {
				parent.layer.msg('移动成功！', {
					icon: 1,
					time: 1000
				});
				getPage(global_path, global_currentPage, global_pageSize, null);

			} else if(res.code == 2) {
				parent.layer.msg('移动失败！请确认mysql和es中的记录是否已修改！', {
					icon: 2,
					time: 1000
				});
			} else if(res.code == 3) {
				parent.layer.msg('移动失败！请确认es中的记录是否已修改！', {
					icon: 2,
					time: 1000
				});
			} else {
				parent.layer.msg('移动失败！', {
					icon: 2,
					time: 1000
				});
			}
		}
	});
}

function _batchSetObjectAcl(aclFlag) {
	var keysStr = "";

	// 获取所有已选中
	var selElements = document.getElementsByClassName('select');
	$(selElements).each(function () {
		if ($(this).css("display") == "block") {
			keysStr = keysStr + "," + $(this).attr("key");
		}
	});

	if (keysStr == null || keysStr == "") {
		parent.layer.msg('请先选择要设置的文件！', {
			icon: 2,
			time: 1000
		});
		return;
	}
	keysStr = keysStr.substring(1);
	batchSetObjectAcl(keysStr, aclFlag);
}

function setObjectAcl_1() {
	var key = $(global_object).attr('key');
    batchSetObjectAcl(key, 1);
}

function setObjectAcl_2() {
	var key = $(global_object).attr('key');
	batchSetObjectAcl(key, 2);
}

var menuItems = [
	{
		type: "item",
		icon: "eye",
		text: "点击预览",
		key: "preview",
		action: preview
	},
	{
		type: "item",
		icon: "copy",
		text: "复制外链",
		key: "copyOuterLink",
		action: copyOuterLink
	},
	{
		type: "item",
		icon: "download",
		text: "下载文件",
		key: "download",
		action: download
	},
	{
		type: "item",
		icon: "hand-stop-o ",
		text: "设为 公有读",
		key: "setObjectAcl_2",
		action: setObjectAcl_2
	},
	{
		type: "item",
		icon: "hand-grab-o ",
		text: "设为 私有读",
		key: "setObjectAcl_1",
		action: setObjectAcl_1
	},
	{
		type: "item",
		icon: "pencil",
		text: "重命名",
		key: "rename",
		action: rename
	},
	{
		type: "item",
		icon: "trash-o",
		text: "删除文件",
		key: "_delete",
		action: _delete
	},
	{
		type: "item",
		icon: "truck",
		text: "移到回收站",
		key: "recycle",
		action: recycle
	}
];

function loadTags() {
	$.ajax({
		type: "POST",
		url: "/cos/listTags",
		dataType: "json",
		async: true,
		success: function (res) {
			if (res.code == 0) {
				// console.log(res);
				var data = res.data;
				$("#tag_list").children().remove();
				for (var i = 0; i < data.length; i++) {
					$("#tag_list").append("<li><a id='tag_" + i + "' href='javascript:void(0);'>" + data[i].text + "</a></li>");
					$("#tag_" + i).attr("onclick", "getPage(" + JSON.stringify(global_path) + ",1," + global_pageSize + "," + JSON.stringify(data[i].text) + ")");
				}
			} else {
				parent.layer.msg('获取标签失败！', {
					icon: 2,
					time: 1000
				});
			}
		}
	});
}

function createImage(url, key) {
	var img = new Image();
	img.alt='image';
	img.classList.add('img-responsive');
	img.src = url;
	img.onerror = function () {
		$.ajax({
			type: "POST",
			url: "/cos/download",
			dataType: "json",
			async: true,
			data: {
				"key": key
			},
			success: function (res) {
				if (res.code == 0) {
					var base64 = res.data.base64;
					var contentType = res.data.contentType;
					img.src = "data:"+contentType+";base64," + base64;
				} else {
					parent.layer.msg('预览图片失败：' + fileName, {
						icon: 2,
						time: 1000
					});
				}
			}
		});
	}
	return img;
}

var isPaginatorExist1 = false;
function getPage(_path, _currentPage, _pageSize, _tag) {
	if(global_is_search) {
		submitSearch(global_cos_type, global_root_path, global_currentPage, global_pageSize);
		return;
	}

	var _url = "/cos/listObjects";

	var _isPreLoad = $('#loading_switch').get(0).checked;
	var _isRecursive = $('#recursive_switch').get(0).checked;

	$.ajax({
		type: "POST",
		url: _url,
		dataType: "json",
		async: true,
		data : {
			"isRecursive" : _isRecursive,
			"dirPath" : _path,
			"currentPage" : _currentPage,
			"pageSize" : _pageSize,
			"tag" : _tag
		},
		success: function(result) {
			if(result.code == 0) {
				console.log(result);
				$("#file_container_id").children().remove();

				var records = result.data.records;
				for(var i = 0; i < records.length; i++) {
					var aclFlag = records[i]['aclFlag'];
					var url = records[i]['url'];
					var key = records[i]['key'];
					var rootPath = records[i]['rootPath'];

					/*var fileName = url.substring(url.lastIndexOf('/')+1);
					if(fileName.lastIndexOf('-') != -1) {
						fileName = fileName.substring(fileName.lastIndexOf('-')+1);
					}*/
					var fileName = records[i]['fileName'];
					var putTime = millisecondsToLocalDate(records[i]['lastModified']);

					if(!url.endsWith('.html')) {
						if(aclFlag == 1) {
							$("#file_container_id").append("<div class='file-box leftClick rightClick' style='position: relative;' onmousedown='setGlobalObject(this)' aclFlag='"+aclFlag+"' fileName='"+fileName+"' rootPath='"+rootPath+"' key='"+key+"' url='"+url+"'> <div id='file_"+i+"' class='file'>  <div class='file-name' align='center'> "+fileName+"<br/><small style='align-content: center;'>"+putTime+"</small> </div> </div> <span style='position:absolute; right:0; top:1%; margin-right: 20px;'> <img style='position: relative; top: 0; right: 0; border: 0;' src='img/ribbon_private.png'> </span><span class='select' key='"+key+"' style='position:absolute; right:0; top:1%; margin-right: 20px; display: none;'url='"+url+"'><img style='position: relative; bottom: 10px; right: 0; border: 0;'src='img/select.png'></span> </div>");
							if(_isPreLoad == true) {
								var icondiv = "<div id='icon_"+i+"' class='image' align='center' style='display:flex;justify-content:center;align-items:center;'></div>";
								$("#file_"+i).prepend(icondiv);
								var img = createImage(url, key);
								$("#icon_"+i).append(img);

							} else {
								var icondiv = "<div id='icon_"+i+"' class='icon' align='center'><i class='fa fa-image'></i></div>";
								$("#file_"+i).prepend(icondiv);
							}
						} else {
							$("#file_container_id").append("<div class='file-box leftClick rightClick' style='position: relative;' onmousedown='setGlobalObject(this)' aclFlag='"+aclFlag+"' fileName='"+fileName+"' rootPath='"+rootPath+"' key='"+key+"' url='"+url+"'> <div id='file_"+i+"' class='file'>  <div class='file-name' align='center'> "+fileName+"<br/><small style='align-content: center;'>"+putTime+"</small> </div> </div> <span style='position:absolute; right:0; top:1%; margin-right: 20px;'> <img style='position: relative; top: 0; right: 0; border: 0;' src='img/ribbon_public.png'> </span><span class='select' key='"+key+"' style='position:absolute; right:0; top:1%; margin-right: 20px; display: none;'url='"+url+"'><img style='position: relative; bottom: 10px; right: 0; border: 0;'src='img/select.png'></span> </div>");
							if(_isPreLoad == true) {
								var icondiv = "<div id='icon_"+i+"' class='image' align='center' style='display:flex;justify-content:center;align-items:center;'></div>";
								$("#file_"+i).prepend(icondiv);
								var img = createImage(url, key);
								$("#icon_"+i).append(img);

							} else {
								var icondiv = "<div id='icon_"+i+"' class='icon' align='center'><i class='fa fa-image'></i></div>";
								$("#file_"+i).prepend(icondiv);
							}
						}
					}
				}

				//左键选中
				$(".leftClick").click(function() {
					var sel = $(this).children('.select'); //获取直接子元素
					if($(sel).css('display') == 'none') {
						$(sel).css('display','block');
					} else {
						$(sel).css('display','none');
					}
				});

				//右键菜单
				$('.file-box').each(function () {
					animationHover(this, 'pulse');
				});
				$(".rightClick").contextMenu({
					items: menuItems
				});

				if(isPaginatorExist1 == false) {
					//构造分页按钮组
					$('#page_element_id2').children().remove();
					var _total = parseInt(result.data.total);
					var page_element = BootstrapPagination($("#page_element_id1"), {
						layoutScheme: "pagesizelist,firstpage,prevgrouppage,prevpage,pagenumber,nextpage,nextgrouppage,lastpage,pageinput,righttext",
						//记录总数。
						total: _total,
						//分页尺寸。指示每页最多显示的记录数量。
						pageSize: _pageSize,
						//当前页索引编号。从0开始的整数。
						pageIndex: _currentPage-1,
						//指示分页导航栏中最多显示的页索引数量。
						pageGroupSize: 5,
						//位于导航条左侧的输出信息格式化字符串
						//leftFormateString: "本页{count}条记录/共{total}条记录",
						//位于导航条右侧的输出信息格式化字符串
						rightFormateString: "共{totalPages}页",
						//页码文本格式化字符串。
						pageNumberFormateString: "{pageNumber}",
						//分页尺寸输出格式化字符串
						pageSizeListFormateString: "{pageSize}条/页",
						//上一页导航按钮文本。
						prevPageText: "上一页",
						//下一页导航按钮文本。
						nextPageText: "下一页",
						//上一组分页导航按钮文本。
						prevGroupPageText: "上一组",
						//下一组分页导航按钮文本。
						nextGroupPageText: "下一组",
						//首页导航按钮文本。
						firstPageText: "首页",
						//尾页导航按钮文本。
						lastPageText: "尾页",
						//设置页码输入框中显示的提示文本。
						pageInputPlaceholder: "go",
						//接受用户输入内容的延迟时间。单位：毫秒
						pageInputTimeout: 1000,
						//分页尺寸列表。
						pageSizeList: [15, 20, 30, 45, 50],
						//当分页更改后引发此事件。
						pageChanged: function (pageIndex, pageSize) {
							getPage(_path, pageIndex + 1, pageSize, _tag);
						},
					});
					isPaginatorExist1 = true;
				}

			} else {
				parent.layer.msg('分页获取文件列表失败！', {
					icon: 2,
					time:1000
				});
			}
		}
	});
}


var isPaginatorExist2 = false;
function submitSearch(_cosType, _rootPath, _currentPage, _pageSize) {
	global_is_search = true;
	var _isPreLoad = $('#loading_switch').get(0).checked;

	global_currentPage = _currentPage;
	global_pageSize = _pageSize;

	var searchContent = $("#search_input_id").val();
	if(!$.trim(searchContent)){ // "",null,undefined
		parent.layer.msg('搜索内容不能为空！', {
			icon: 2,
			time:1000
		});
		$("#search_input_id").val("");
		$("#search_input_id").focus();
	} else {
		$.ajax({
			type : "POST",
			url : "/cos/search",
			async : true,
			data : { //使用Json格式进行透传
				"searchContent" : searchContent,
				"cosType" : _cosType,
				"rootPath" : _rootPath,
				"currentPage" : _currentPage,
				"pageSize" : _pageSize
			},
			dataType:"json",
			success : function(result) {
				console.log(result);
				if (result.code==0) {
					$("#file_container_id").children().remove();
					var records = result.data.records;
					for(var i = 0; i < records.length; i++) {
						var aclFlag = records[i]['aclFlag'];
						var url = records[i]['url'];
						var key = records[i]['key'];
						var rootPath = records[i]['rootPath'];
						var fileName = records[i]['fileName'];
						var _fileName = fileName.replace(/<[^>]+>/g,""); //去除html标签
						var putTime = millisecondsToLocalDate(records[i]['lastModified']);

						if(!url.endsWith('.html')) {
							if(aclFlag == 1) {
								$("#file_container_id").append("<div class='file-box leftClick rightClick' style='position: relative;' onmousedown='setGlobalObject(this)' aclFlag='"+aclFlag+"' fileName='"+_fileName+"' rootPath='"+rootPath+"' key='"+key+"' url='"+url+"'> <div id='file_"+i+"' class='file'>  <div class='file-name' align='center'> "+fileName+"<br/><small style='align-content: center;'>"+putTime+"</small> </div> </div> <span style='position:absolute; right:0; top:1%; margin-right: 20px;'> <img style='position: relative; top: 0; right: 0; border: 0;' src='img/ribbon_private.png'> </span><span class='select' key='"+key+"' style='position:absolute; right:0; top:1%; margin-right: 20px; display: none;'url='"+url+"'><img style='position: relative; bottom: 10px; right: 0; border: 0;'src='img/select.png'></span> </div>");
								if(_isPreLoad == true) {
									var icondiv = "<div id='icon_"+i+"' class='image' align='center' style='display:flex;justify-content:center;align-items:center;'></div>";
									$("#file_"+i).prepend(icondiv);
									var img = createImage(url, key);
									$("#icon_"+i).append(img);

								} else {
									var icondiv = "<div id='icon_"+i+"' class='icon' align='center'><i class='fa fa-image'></i></div>";
									$("#file_"+i).prepend(icondiv);
								}
							} else {
								$("#file_container_id").append("<div class='file-box leftClick rightClick' style='position: relative;' onmousedown='setGlobalObject(this)' aclFlag='"+aclFlag+"' fileName='"+_fileName+"' rootPath='"+rootPath+"' key='"+key+"' url='"+url+"'> <div id='file_"+i+"' class='file'>  <div class='file-name' align='center'> "+fileName+"<br/><small style='align-content: center;'>"+putTime+"</small> </div> </div> <span style='position:absolute; right:0; top:1%; margin-right: 20px;'> <img style='position: relative; top: 0; right: 0; border: 0;' src='img/ribbon_public.png'> </span><span class='select' key='"+key+"' style='position:absolute; right:0; top:1%; margin-right: 20px; display: none;'url='"+url+"'><img style='position: relative; bottom: 10px; right: 0; border: 0;'src='img/select.png'></span> </div>");
								if(_isPreLoad == true) {
									var icondiv = "<div id='icon_"+i+"' class='image' align='center' style='display:flex;justify-content:center;align-items:center;'></div>";
									$("#file_"+i).prepend(icondiv);
									var img = createImage(url, key);
									$("#icon_"+i).append(img);

								} else {
									var icondiv = "<div id='icon_"+i+"' class='icon' align='center'><i class='fa fa-image'></i></div>";
									$("#file_"+i).prepend(icondiv);
								}
							}
						}
					}

					//左键选中
					$(".leftClick").click(function() {
						var sel = $(this).children('.select'); //获取直接子元素
						if($(sel).css('display') == 'none') {
							$(sel).css('display','block');
						} else {
							$(sel).css('display','none');
						}
					});

					//右键菜单
					$('.file-box').each(function () {
						animationHover(this, 'pulse');
					});
					$(".rightClick").contextMenu({
						items: menuItems
					});

					if(isPaginatorExist2 == false) {
						//构造分页按钮组
						$('#page_element_id1').children().remove();
						var total = parseInt(result.data.total);
						var page_element = BootstrapPagination($("#page_element_id2"), {
							layoutScheme: "pagesizelist,firstpage,prevgrouppage,prevpage,pagenumber,nextpage,nextgrouppage,lastpage,pageinput,righttext",
							//记录总数。
							total: total,
							//分页尺寸。指示每页最多显示的记录数量。
							pageSize: _pageSize,
							//当前页索引编号。从0开始的整数。
							pageIndex: _currentPage-1,
							//指示分页导航栏中最多显示的页索引数量。
							pageGroupSize: 10,
							//位于导航条左侧的输出信息格式化字符串
							//leftFormateString: "本页{count}条记录/共{total}条记录",
							//位于导航条右侧的输出信息格式化字符串
							rightFormateString: "共{totalPages}页",
							//页码文本格式化字符串。
							pageNumberFormateString: "{pageNumber}",
							//分页尺寸输出格式化字符串
							pageSizeListFormateString: "{pageSize}条/页",
							//上一页导航按钮文本。
							prevPageText: "上一页",
							//下一页导航按钮文本。
							nextPageText: "下一页",
							//上一组分页导航按钮文本。
							prevGroupPageText: "上一组",
							//下一组分页导航按钮文本。
							nextGroupPageText: "下一组",
							//首页导航按钮文本。
							firstPageText: "首页",
							//尾页导航按钮文本。
							lastPageText: "尾页",
							//设置页码输入框中显示的提示文本。
							pageInputPlaceholder: "go",
							//接受用户输入内容的延迟时间。单位：毫秒
							pageInputTimeout: 1000,
							//分页尺寸列表。
							pageSizeList: [15, 20, 30, 45, 50],
							//当分页更改后引发此事件。
							pageChanged: function (pageIndex, pageSize) { //pageIndex从0开始
								submitSearch(_cosType, _rootPath, pageIndex+1, pageSize);
							},
						});
						isPaginatorExist2 = true;
					}
				}
			}
		});
	}
}

function batchSetObjectAcl(keysStr, aclFlag) {
    $.ajax({
        type: "POST",
        url: "/cos/batchSetObjectAcl",
        dataType: "json",
        async: true,
        data : {
            "keysStr" : keysStr,
            "aclFlag" : aclFlag
        },
        success: function(result) {
            if(result.code == 0) {
                parent.layer.msg('设置成功！', {
                    icon: 1,
                    time:1000
                });
                if(keysStr.endsWith('/')) {
                    $('#jstree').jstree('refresh');
                } else {
                    getPage(global_path, global_currentPage, global_pageSize, null);
                }

            } else if (result.code == 1) {
                parent.layer.msg('设置失败！同步COS端权限失败！', {
                    icon: 2,
                    time:1000
                });
            } else if (result.code == 2) {
				parent.layer.msg('设置失败！同步MYSQL及ES端权限失败！', {
					icon: 2,
					time:1000
				});
			} else if (result.code == 3) {
				parent.layer.msg('设置失败！同步ES端权限失败！', {
					icon: 2,
					time:1000
				});
			}
        }
    });
}

function connect_to_sse_server(eventId) {
	var eventSource = new EventSource('/sse/event/' + eventId, { withCredentials: true });

	eventSource.addEventListener('open', function (evt) {
		console.log('sse server connected')
	});

	eventSource.addEventListener("message", function (evt) {
		var data = evt.data;
		var resp = JSON.parse(data);

		console.log(resp);

		if(resp.payload.code == 0) {
			bootoast({
				message: 'Delete success!',
				type: 'success',
				position:'right-top',
				timeout:3
			});
			$('#jstree').jstree('refresh');
		} else {
			bootoast({
				message: 'Delete failed!',
				type: 'danger',
				position:'right-top',
				timeout:3
			});
		}

		eventSource.close();
	});

	eventSource.addEventListener('error', function (evt) {
		console.log('sse server disconnected')
	});
}

/**
 * 建立websocket连接
 *
 * @param sub_address 服务端向客户端推送消息的地址，例如 '/notice/xxx'
 */
function connect_to_wb_server(sub_address) {
	var socket = new SockJS('/wb_endpoint');
	var stompClient = Stomp.over(socket);

	//窗口关闭时，关闭连接，否则java后台会报错
	window.onbeforeunload = function() {
		disconnect_to_wb_server();
	}

	stompClient.connect({}, function (frame) {
		console.log("Connected!");
		var headers = {'id' : sub_address}; //这里指定subscription_id的值，也即回调函数的result.headers.subscription值
		stompClient.subscribe(sub_address, function (result) {
			var resp = JSON.parse(result.body);
			if(resp.payload.code == 0) {
				bootoast({
					message: 'Delete success!',
					type: 'success',
					position:'right-top',
					timeout:3
				});
				$('#jstree').jstree('refresh');
			} else {
				bootoast({
					message: 'Delete failed!',
					type: 'danger',
					position:'right-top',
					timeout:3
				});
			}
			disconnect_to_wb_server(stompClient);

		}, headers);

	}, function () { //非代码里手动关闭，则循环重连，除非关闭窗口
		connect_to_wb_server(sub_address);
	});
}

/**
 * 关闭websocket连接
 *
 * @param stompClient
 */
function disconnect_to_wb_server(stompClient) {
	if (stompClient !== null) {
		for(var sub in stompClient.subscriptions) { //取消所有订阅
			if (stompClient.subscriptions.hasOwnProperty(sub)) {
				stompClient.unsubscribe(sub);
			}
		}
		stompClient.disconnect();
		console.log("Disconnected!");
	}
}

// 2、目录树
$(document).ready(function () {
    $('#jstree').jstree({ //生成jstree
        'core': {
            'check_callback': true,
            'data' : function (obj, callback) {
                $.ajax({
                    type: "POST",
                    url: "/cos/getDirectoryTree",
                    dataType: "json",
                    async: true,
                    data : {
		            	"rootDirPath" : "image/",
		            },
                    success: function(result) {
                    	if(result.code == 0) {
                    		// console.log(result);
                        	var jsonArray = [];
                            var nodes= result.data;
                            for(var i=0 ; i<nodes.length; i++) {
                                var _json = {
                                    "id" : nodes[i].id,
                                    "parent" : nodes[i].parentId==null ? "#" : nodes[i].parentId,
                                    "text" : nodes[i].fileName,
                                    "state" : {"opened" : true}
                                }
                                if(nodes[i].aclFlag == 1) {
                                	_json.icon = "fa fa-lock";
                                } else if(nodes[i].aclFlag == 2) {
                                	_json.icon = "fa fa-unlock-alt";
                                } else if(nodes[i].aclFlag == 3) {
                                	_json.icon = "fa fa-unlock";
                                } 
                                jsonArray.push(_json);
	                        }
                            callback.call(this, jsonArray);

                        } else {
                        	parent.layer.msg('建立COS目录树失败！', {
							    icon: 2,
								time:1000
							});
                        }
                    }
                });
            }
        },
        'plugins': ['types', 'contextmenu'],
        'types': {
            'default': {
                'icon': 'fa fa-folder'
            }
        },
        "contextmenu":{ //自定义右键菜单项
		  "items":{
		    	"Create":{
                    "label":"新建目录",
                    "action":function(data){
                        var node = $('#jstree').jstree('get_node',data.reference[0])
//                          var pid = node.parent;
//                          console.log(pid, node.text);
						var names = $('#jstree').jstree('get_path', node, '/', false)
//		    				console.log(names.replace(/\s*/g,""));
						var path = names.replace(/\s*/g,"");
	    				
	    				//
	    				var instance = $.jstree.reference(data.reference);
						obj = instance.get_node(data.reference);
						var new_node_id = instance.create_node(obj, {}, "last", function (new_node) {
							new_node.text = "新建目录";
							instance.edit(new_node, "新建目录", function (_node,_status,_cancel) {
								if(_status) {
									$.ajax({
										type: "POST",
										url: "/cos/createDirectory",
										dataType: "json",
										async: true,
										data : {
											"parentDirPath" : path + "/",
											"parentId" : node.id,
											"newDirName" : _node.text
										},
										success: function(result) {
											if(result.code == 0) {
												parent.layer.msg('新建成功！', {
													icon: 1,
													time:1000
												});
												$('#jstree').jstree('refresh');
											} else {
												parent.layer.msg('新建失败！', {
													icon: 2,
													time:1000
												});
												instance.delete_node(new_node);
											}
										}
									});
								} else {
									parent.layer.msg('新建失败！', {
										icon: 2,
										time:1000
									});
									instance.delete_node(new_node);
								}
							});
						});
	    				//
                    }
                },
		        "Delete":{
                    "label":"删除目录",
                    "action":function(data) {
                        var node = $('#jstree').jstree('get_node',data.reference[0])
                    	var names = $('#jstree').jstree('get_path', node, '/', false)
                    	var path = names.replace(/\s*/g,"");
//                      	console.log(path);
                    	//
                    	parent.layer.confirm('同时会删除该目录下所有子目录及子文件，确定删除吗？', {
                    		icon: 0,
						  	btn: ['确定','取消'] //按钮
						}, function() {
                    		// var eventId = genUuid();
							// connect_to_sse_server(eventId);
							var sub_address = '/notice/'+ genUuid();
							connect_to_wb_server(sub_address);
							$.ajax({
								type: "POST",
								url: "/cos/deleteDirectory",
								dataType: "json",
								async: true,
								data : {
									"targetDirPath" : path + "/",
									// "eventId" : eventId
									"subAddress" : sub_address
								},
								success: function(result) {
									if(result.code == 0) {
										parent.layer.msg('删除命令发送成功！正在删除中，请稍后...', {
											icon: 1,
											time:2000
										});
										/*var instance = $.jstree.reference(data.reference);
										obj = instance.get_node(data.reference);
										var isSuccess = instance.delete_node(obj);*/
										// $('#jstree').jstree('refresh');
									} else {
										parent.layer.msg('删除命令发送失败！', {
											icon: 2,
											time:2000
										});
									}
								}
							});
						});
                    	//
                    }
                },
                "Access control":{
            		"label":"权限控制",
            		"submenu" : {
            			"PublicReadPrivateWrite" : {
            				"label":"设为 公有读",
	                        "action":function(data) {
	                            var node = $('#jstree').jstree('get_node',data.reference[0])
	                            var names = $('#jstree').jstree('get_path', node, '/', false)
//				    				console.log(names.replace(/\s*/g,""));
								var path = names.replace(/\s*/g,"");
								
								//
								batchSetObjectAcl(path + "/", 2);
								//
	                        }
            			},
            			"PrivateReadPrivateWrite" : {
            				"label":"设为 私有读",
	                        "action":function(data) {
	                            var node = $('#jstree').jstree('get_node',data.reference[0])
	                            var names = $('#jstree').jstree('get_path', node, '/', false)
//				    				console.log(names.replace(/\s*/g,""));
								var path = names.replace(/\s*/g,"");
								
								//
								batchSetObjectAcl(path + "/", 1);
								//
	                        }
            			}
                   }
                }
		  	}
		}
    }).bind("activate_node.jstree", function (obj, data) { //绑定单击事件
    	if('click'==data.event.type) { //判断是否是左键
		    var ids = data.instance.get_path(data.node,'/',true)
		    var names = data.instance.get_path(data.node, '/', false)
//		    console.log(ids.replace(/\s*/g,""));
//			    console.log(names.replace(/\s*/g,""));
			var path = names.replace(/\s*/g,"");
			global_path = path+"/";
		    
		    //
			global_is_search = false;
			getPage(global_path, global_currentPage, global_pageSize, null);
			loadTags();
			//
	    }
	}).on('loaded.jstree', function(e, data) { //目录树加载完毕后默认选中根节点
    	var obj = data.instance.get_node(e.target.firstChild.firstChild.lastChild);
    	data.instance.select_node(obj);
    	
    	var names = data.instance.get_path(obj, '/', false)
		var path = names.replace(/\s*/g,"");
		global_path = path+"/";
//		console.log(path);
    	//
		global_is_search = false;
		getPage(global_path, 1, 15, null);
		loadTags();
		//
   });

	//刷新目录树的按钮事件
	$('#refresh_id').click(function () {
		btn = $(this);
		btn.children().addClass('fa-spin');
		//
		$('#jstree').jstree('refresh');
		//
		window.setTimeout(function () {
			btn.children().removeClass('fa-spin');
		}, 1000);
	});


	//下拉菜单中的目录树
	$('#menu_tree_id').jstree({ //生成jstree
		'core': {
			'check_callback': true,
			'data' : function (obj, callback) {
				$.ajax({
					type: "POST",
					url: "/cos/getDirectoryTree",
					dataType: "json",
					async: true,
					data : {
						"rootDirPath" : "image/",
					},
					success: function(result) {
						if(result.code == 0) {
							// console.log(result);
							var jsonArray = [];
							var nodes= result.data;
							for(var i=0 ; i<nodes.length; i++) {
								var _json = {
									"id" : nodes[i].id,
									"parent" : nodes[i].parentId==null ? "#" : nodes[i].parentId,
									"text" : nodes[i].fileName,
									"state" : {"opened" : true}
								}
								if(nodes[i].aclFlag == 1) {
									_json.icon = "fa fa-lock";
								} else if(nodes[i].aclFlag == 2) {
									_json.icon = "fa fa-unlock-alt";
								} else if(nodes[i].aclFlag == 3) {
									_json.icon = "fa fa-unlock";
								}
								jsonArray.push(_json);
							}
							callback.call(this, jsonArray);

						} else {
							parent.layer.msg('建立COS目录树失败！', {
								icon: 2,
								time:1000
							});
						}
					}
				});
			}
		},
		'plugins': ['types'],
		'types': {
			'default': {
				'icon': 'fa fa-folder'
			}
		},
	}).bind("activate_node.jstree", function (obj, data) { //绑定单击事件
		if('click'==data.event.type) { //判断是否是左键
			var ids = data.instance.get_path(data.node,'/',true)
			var names = data.instance.get_path(data.node, '/', false)
			var path = names.replace(/\s*/g,"") + "/";

			//
			var keysStr = "";
			var selElements = document.getElementsByClassName('select');
			$(selElements).each(function () {
				if ($(this).css("display") == "block") {
					keysStr = keysStr + "," + $(this).attr("key");
				}
			});
			if (keysStr == null || keysStr == "") {
				parent.layer.msg('请先选择要移动的文件！', {
					icon: 2,
					time: 1000
				});
				return;
			}
			keysStr = keysStr.substring(1);
			batch_move(keysStr, path)
			//
		}
	});

});


function webUploader() {
	layer.confirm('当前选择的路径是\''+global_path+'\'，确定吗？', {icon: 3, title:'重要'}, function(index) {
		is_upload_success = false;
  		layer.open({
		  type: 2,
		  title: '上传图片',
		  shadeClose: true,
		  shade: 0.5,
		  area: ['50%', '570px'],
		  content: 'web_uploader.html',
		  end: function() { //关闭上传窗口的回调
		  	if(is_upload_success) {
		  		//
				getPage(global_path, global_currentPage, global_pageSize, null);
				//
		  	}
		  }
		});
	  	layer.close(index);
	});
}


</script>

</body>

</html>
